import Vue from 'vue'
import moment from 'moment'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')


// 数字序列化
Vue.filter('NumberFormat', function (value) {
  if (!value) {
    return '0'
  }
  const intPartFormat = value.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') // 将整数部分逢三一断
  return intPartFormat
})


// moment.js 遍历时间
Vue.filter('date', function (dataStr, pattern = 'YYYY-MM-DD') {
  return dataStr ?  moment(dataStr).format(pattern) : ''
})
Vue.filter('datetime', function (dataStr, pattern = 'YYYY-MM-DD HH:mm') {
  return dataStr ?  moment(dataStr).format(pattern) : ''
})


// 首字母大写
Vue.filter('capitalize', function (value) {
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})


// 保留小数位数
Vue.filter('toFixed', function (val, acc) {  // acc为保留几位小数位
  let num = parseFloat(val);
  if (isNaN(num)) {
      num = 0;
  }
  let accuracy = parseInt(acc)
  if (isNaN(accuracy) || accuracy < 0 || accuracy > 10) {
      accuracy = 2
  }
  return num.toFixed(accuracy)
})


// 小数转百分比
Vue.filter('toPercent', function (val, acc) {  // acc为保留小数位
  let num = parseFloat(val)
  if (isNaN(num)) {
    num = 0
  }   
  let accuracy = parseInt(acc)
  if (isNaN(accuracy) || accuracy < 0 || accuracy > 10) {
    accuracy = 2
  }
  return (num * 100).toFixed(accuracy) + "%"
})